package com.zxp.pstationapk.retrofit;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.zxp.pstationapk.bean.ProgressBean;

import java.lang.ref.WeakReference;

/**
 * @author: Created by EDZ on 2018/7/17.
 * function:
 */

public abstract class ProgressHandler {
    private static final int DOWNLOAD_PROGRESS = 1;

    protected abstract void onProgress(long progress, long total, long speed, boolean done);

    private final Handler mHandler = new UIHandler(Looper.getMainLooper(), this);

    protected void sendMessage(ProgressBean progressBean) {
        mHandler.obtainMessage(DOWNLOAD_PROGRESS, progressBean).sendToTarget();
    }

    static class UIHandler extends Handler {
        private final WeakReference<ProgressHandler> mProgressHandler;

        public UIHandler(Looper looper, ProgressHandler progressHandler) {
            super(looper);
            mProgressHandler = new WeakReference<ProgressHandler>(progressHandler);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_PROGRESS:
                    ProgressHandler progressHandler = mProgressHandler.get();
                    if (progressHandler != null) {
                        ProgressBean progressBean = (ProgressBean) msg.obj;
                        progressHandler.onProgress(progressBean.getBytesRead(), progressBean.getContentLength(), progressBean.getSpeed(), progressBean.isDone());
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
